package com.ccys.cms.service.corporateAndInsurance.impl;

import cn.hutool.core.util.IdUtil;
import com.ccys.cms.service.corporateAndInsurance.PlanService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.corporateAndInsurance.PlanDto;
import com.ccys.db.entity.TblPlan;
import com.ccys.db.mapper.TblPlanMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.vo.corporateAndInsurance.PlanVo;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
public class PlanServiceImpl extends BaseServiceImpl<TblPlan> implements PlanService {

    @Resource
    private TblPlanMapper mapper;

    @Override
    public ResponseResult getPage(PlanDto dto) {
        PageDto.startPage();
        List<PlanVo> list = mapper.getList(dto);
        PageInfo<PlanVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    public ResponseResult change(TblPlan model) {

        if (StringUtils.isEmpty(model.getId()) && model.getType() != 1) {
            model.setPolicyNo(IdUtil.getSnowflakeNextIdStr());
        }
        //判断AIA corporate的policy no是否重复
        if (model.getType() == 1) {
            if (StringUtils.isEmpty(model.getId())) {
                List<TblPlan> planList = this.findListByLimit(TblPlan.class, new ArrayList<String>() {{
                    add("del_flag = 0");
                    add("  policy_no = '" + model.getPolicyNo() + "'");
                }}, "created_on desc");
                if (CollectionUtils.isNotEmpty(planList)) {
                    return ResponseResult.error(" policyNo already exists ");
                }
            } else {
                List<TblPlan> planList = this.findListByLimit(TblPlan.class, new ArrayList<String>() {{
                    add("del_flag = 0");
                    add("  policy_no = '" + model.getPolicyNo() + "'");
                    add(" id != '" + model.getId() + "'");
                }}, "created_on desc");
                if (CollectionUtils.isNotEmpty(planList)) {
                    return ResponseResult.error(" policyNo already exists ");
                }
            }

        }
        int i = this.insertOrUpdate(model);
        return ResponseResult.update(i);


    }
}
